package com.jeedle.nahe;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
//import android.app.DialogFragment;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private static final String HTML_CONTENT = "com.jeedle.nahe.HTMLCONTENT";
	private static final String HOTKEYS_VISIBILITY = "com.jeedle.nahe.HOTKEYS_VISIBILITY";
	public static final int PICK_FILE_NAME = 1;
	public static String starting_folder =".";
	MultiAutoCompleteTextView v;
	private boolean hotKeysEnabled;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		ArrayAdapter<CustomString> adapter = new ArrayAdapter<CustomString>(this
				                                                             ,android.R.layout.simple_spinner_item
				                                                             ,HTMLTags.tags);
		v = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
		v.setGravity(Gravity.TOP);
		v.setMovementMethod(new ScrollingMovementMethod());
		v.setAdapter(adapter);
        v.clearFocus();
		v.setTokenizer(new SpaceTokenizer());
		
		this.restoreHtmlContentFromPreviousInstance();
		this.restoreHotkeysVisibilityFromPreviousInstance();
		this.setHtmlHotKeysVisibility();
		this.addOnclickEventsToHotKeys();
	}

	@Override
	protected void onStop() {
		super.onStop();
		this.saveHtmlContentForFutureInstance();
		this.saveHotkeyPanelVisibilityForFutureInstance();
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
	    savedInstanceState.putString(HTML_CONTENT, this.getHTMLContent());
	    super.onSaveInstanceState(savedInstanceState);
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		this.restoreHtmlContentFromPreviousInstance();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.main, menu);
		MenuItem htmlHotKeysItem = (MenuItem) menu.findItem(R.id.html_hot_keys);
		htmlHotKeysItem.setChecked(this.hotKeysEnabled);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
		    case R.id.open_web_view:
		        this.openWebView();
   		        return true;
		    case R.id.open_browser_view:
		        this.viewInDefaultWebBrowser();
   		        return true;
		    case R.id.SaveItem:
		    	this.SaveFile();
		    	return true;
		    case R.id.OpenItem:
		    	this.OpenFile();
		    	return true;
		    case R.id.html_hot_keys:
		    	item.setChecked(!item.isChecked());
		    	this.hotKeysEnabled = item.isChecked();
		    	this.setHtmlHotKeysVisibility();
		    	return true;
		    default:
		        return super.onOptionsItemSelected(item);
	    }
	}

	private void setHtmlHotKeysVisibility() {
		//LinearLayout topLayout = (LinearLayout) findViewById(R.id.hotKeysTopContainer);
		HorizontalScrollView bottomLayout = (HorizontalScrollView) findViewById(R.id.hotKeysTopContainer);
		
		if(this.hotKeysEnabled == true) {
		//	topLayout.setVisibility(LinearLayout.VISIBLE);
			bottomLayout.setVisibility(LinearLayout.VISIBLE);
		}
		else {
			//topLayout.setVisibility(LinearLayout.INVISIBLE);
			bottomLayout.setVisibility(LinearLayout.INVISIBLE);
		}
		LinearLayout mainContainer = (LinearLayout) findViewById(R.id.mainContainer);
		mainContainer.invalidate();
	}

	/* Save/Restore methods */
	private void saveHtmlContentForFutureInstance(){
		SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putString(HTML_CONTENT, this.getHTMLContent());
		editor.commit();
	} 
	
	private void saveHotkeyPanelVisibilityForFutureInstance() {
		SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPref.edit();
		editor.putBoolean(HOTKEYS_VISIBILITY, this.hotKeysEnabled);
		editor.commit();		
	}
	
	private void restoreHtmlContentFromPreviousInstance(){
		SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
	    String htmlContent = sharedPref.getString(HTML_CONTENT, null);
	    MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
	    textView.setText(htmlContent);
	}
	
	private void restoreHotkeysVisibilityFromPreviousInstance(){
		SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
		this.hotKeysEnabled = sharedPref.getBoolean(HOTKEYS_VISIBILITY, false);
	}
	
	/**
	 * @return String
	 */
	private String getHTMLContent(){
	    MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
	    return textView.getText().toString();
	}
	
	private void openWebView(){
	    Intent intent = new Intent(this, WebViewer.class);
	    String htmlContent = this.getHTMLContent();
	    intent.putExtra(HTML_CONTENT, htmlContent);
	    startActivity(intent);
	}


   private void SaveFile()
   {
	   DialogFragment save = new SaveFileFragment();
	   save.show(getSupportFragmentManager(), "SaveDialog");
   }
   private void OpenFile()
   {
	   Intent intent = new Intent(this, OpenFileDialog.class);
	   //intent.putExtra("FilePath", starting_folder);
	   startActivityForResult (intent,PICK_FILE_NAME);
   }
   
   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     switch(requestCode) {
       case (PICK_FILE_NAME) : {
         if (resultCode == PICK_FILE_NAME && resultCode != RESULT_CANCELED) {
           // TODO Extract the data returned from the child Activity.
        	  String t = data.getExtras().getString("fileText");
        	  starting_folder = data.getExtras().getString("FilePath");
        	  v.setText(t);
         }
         break;
       } 
     }
   }


/*	private void SaveFile() {
		DialogFragment save = new SaveFileFragment();
		save.show(getSupportFragmentManager(), "SaveDialog");
	}*/
/*
	private void OpenFile()	{
		Intent intent = new Intent(this, OpenFileDialog.class);
		startActivityForResult (intent,PICK_FILE_NAME);
	}*/

/*	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode) {
			case (PICK_FILE_NAME) : {
				if (resultCode == PICK_FILE_NAME) {
					// TODO Extract the data returned from the child Activity.
					String t = data.getExtras().getString("fileText");
					v.setText(t);
				}
				break;
			} 
		}
	}*/

	private void addOnclickEventsToHotKeys() {
		((Button) findViewById(R.id.greaterThanHK)).setOnClickListener(this);
		//((Button) findViewById(R.id.lesserThanHK)).setOnClickListener(this);
		((Button) findViewById(R.id.lessThanHK)).setOnClickListener(this);
		((Button) findViewById(R.id.forwardSlashHK)).setOnClickListener(this);
		((Button) findViewById(R.id.tabHK)).setOnClickListener(this);
		((Button) findViewById(R.id.enterTabHK)).setOnClickListener(this);
		((Button) findViewById(R.id.singleQuoteHK)).setOnClickListener(this);
		((Button) findViewById(R.id.doubleQuoteHK)).setOnClickListener(this);
		((Button) findViewById(R.id.dashHK)).setOnClickListener(this);
		((Button) findViewById(R.id.underScoreHK)).setOnClickListener(this);
		((Button) findViewById(R.id.equalSignHK)).setOnClickListener(this);
	}
	
	@Override
	public void onClick(View view) {
	    MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.multiAutoCompleteTextView1);
	    String stringToInsert = "";
	    if ( textView.getSelectionStart() == -1)
	    {
	    	textView.requestFocus();
	    }
		switch(view.getId()) {
			case R.id.greaterThanHK:
				stringToInsert = ">";
				break;

			case R.id.lessThanHK:
				stringToInsert = "<";
				break;
			
			case R.id.forwardSlashHK:
				dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SLASH));
				break;
			
			case R.id.tabHK:
				stringToInsert = "\t";
				break;
			
			case R.id.enterTabHK:
				String content = textView.getText().toString();
				int endFill = textView.getSelectionStart() -1;
				int startFill = content.lastIndexOf("\n", endFill);
				
				if (startFill ==-1)
				{
					startFill = 0;
				}
				
				String lineUpToPointer =  content.substring(startFill, endFill+1);
				Pattern p = Pattern.compile( "\\S" );
				Matcher m = p.matcher( lineUpToPointer );
				int position = 1;
				if( m.find() ) { position = m.start(); }
				
				if (position == 0)
				{
					position = 1;
				}
				lineUpToPointer = lineUpToPointer.substring(0, position-1);
				stringToInsert += lineUpToPointer.length() < 2 ? "\n" : lineUpToPointer + " ";
				break;

			case R.id.singleQuoteHK:
				dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_APOSTROPHE));
				break;
			
			case R.id.doubleQuoteHK:
				stringToInsert = "\"";
				break;
			
			case R.id.dashHK:
				dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MINUS));
				break;

			case R.id.underScoreHK:
				stringToInsert = "_";
				break;
			
			case R.id.equalSignHK:
				dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_EQUALS));
				break;
		}

		int start = textView.getSelectionStart();
	    int end = textView.getSelectionEnd();
	    
		if(stringToInsert.length() > 0 && (start >=0 && end >=0))
		{
		    textView.getText().replace(Math.min(start, end), Math.max(start, end), stringToInsert, 0, stringToInsert.length());
			textView.requestFocus();					
		}
       // if the start and end variables are -1, the textarea does not have the focus.
	   // ask the user to touch on the screen to set the focus on the textview.
		else if (start ==-1 && end ==-1)
		{
			Toast.makeText(MainActivity.this, "Touch on the on the text area to start typing",Toast.LENGTH_LONG).show();
			textView.requestFocus();	
		}
	}
	
	private void viewInDefaultWebBrowser()
	{
		/** TO BE SUBSTITUTED WITH ACTUAL FILE PATH !!! */
		String path = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "//html/doc1.html";
		
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse( path ));
        i.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        startActivity(i);
	}
	
	
}
